package com.huawei.common.interceptors;

import cn.hutool.core.util.StrUtil;
import com.huawei.common.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

public class UserInfoInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println(request.getRequestURI());
        String[] userInfo = new String[3];
        userInfo[0] = request.getHeader("id");
        userInfo[1] = request.getHeader("username");
        userInfo[2] = request.getHeader("Authorization");
        System.out.println("id: " + userInfo[0] + "令牌：" + userInfo[1]);
        if(StrUtil.isNotBlank(userInfo[0]) && StrUtil.isNotBlank(userInfo[1]) && StrUtil.isNotBlank(userInfo[2])){
            ThreadLocalUtil.set(userInfo);
            //TODO: 刷新token有效期
        }
        return true;
    }


    //不能用posthandle，因为如果controller层出现了异常，
    // posthandle方法不会执行，而aftercompletion会执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
